//
//  AVMovieViewController.m
//  LZMPro
//
//  Created by dllo on 15/11/11.
//  Copyright © 2015年 LZS. All rights reserved.
//

#import "AVMovieViewController.h"
#import "MovieModel.h"
#import <AVFoundation/AVFoundation.h>

@interface AVMovieViewController ()<UITableViewDelegate, UITableViewDataSource>
{
    NSDateFormatter *_dateFormatter;
}

//播放器
@property(nonatomic, strong) AVPlayer *player;

//播放器容器
@property(nonatomic, strong) UIView *container;

//播放/暂停按钮
@property(nonatomic, strong) UIButton *playPause;
//时间显示
@property(nonatomic, strong) UILabel *timeLabel;
//滑动块
@property(nonatomic, strong) UISlider *slider;
//进度条
@property(nonatomic, strong) UISlider *progress;

//顶部视图
@property(nonatomic, strong) UIView *topView;
//底部视图
@property(nonatomic, strong) UIView *downView;
//标题框
@property(nonatomic, strong) UILabel *titleLabel;

//返回按钮
@property(nonatomic, strong) UIButton *backButton;

//选择/切换视频按钮
@property(nonatomic, strong) UIButton *selectedButton;
//提示框
@property(nonatomic, strong) UILabel  *messageMark;
//是否正在操作
@property(nonatomic, assign) BOOL isOperation;

//选集tableView
@property(nonatomic, strong) UITableView *myTableView;
//观察者
@property(nonatomic, strong) id playBackObserver;

/** 隐藏计数 */
@property (assign, nonatomic) NSInteger hiddenCount;

@end

@implementation AVMovieViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor blackColor];
    self.hiddenCount = 0;
    self.isOperation = NO;
    
    self.messageMark = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 40)];
    self.messageMark.center = CGPointMake(667 / 2, 375 / 2);
    self.messageMark.layer.masksToBounds = YES;
    self.messageMark.layer.cornerRadius = 10;
    self.messageMark.textColor = [UIColor whiteColor];
    self.messageMark.textAlignment = NSTextAlignmentCenter;
    self.messageMark.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.5];
    [self.view addSubview:self.messageMark];
    
    [self createSubViews];
    [self initMytableView];
    [_player play];
    //关闭用户交互
    [self userEnble];
}

-(void)createSubViews{
    //播放器容器
    self.container = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CURRENTHEIGHT, CURRENTWIDTH)];
    [self.view addSubview:self.container];
    //创建播放器层
    [self setPlaySubviews];
    
    //顶部视图
    self.topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CURRENTHEIGHT, 50)];
    self.topView.backgroundColor = [UIColor blackColor];
    self.topView.alpha = 0.4;
    [self.view addSubview:self.topView];
    
    //返回按钮
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.backButton setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    self.backButton.frame = CGRectMake(0, 0, 60, 30);
    [self.backButton addTarget:self action:@selector(backButtonAction) forControlEvents:UIControlEventTouchUpInside];
    [self.topView addSubview:self.backButton];
    
    //标题
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 10, CURRENTHEIGHT - 200, 30)];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:18];
    [self.topView addSubview:self.titleLabel];
    
    //选集按钮
    self.selectedButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.selectedButton.layer.borderColor = [UIColor whiteColor].CGColor;
    self.selectedButton.layer.borderWidth = 2;
    self.selectedButton.titleLabel.font = [UIFont systemFontOfSize:15];
    self.selectedButton.frame = CGRectMake(667 - 70, 15, 50, 20);
    [self.selectedButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.selectedButton setTitle:@"选集" forState:UIControlStateNormal];
    [self.selectedButton addTarget:self action:@selector(selectedAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.topView addSubview:self.selectedButton];
    
    //底部视图
    self.downView = [[UIView alloc] initWithFrame:CGRectMake(0, CURRENTWIDTH - 60, CURRENTHEIGHT, 60)];
    self.downView.backgroundColor = [UIColor blackColor];
    self.downView.alpha = 0.4;
    [self.view addSubview:self.downView];
    
    //播放/停止按钮
    self.playPause = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.playPause setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
    self.playPause.frame = CGRectMake(5, 5, 50, 50);
    [self.playPause addTarget:self action:@selector(playPauseAction) forControlEvents:UIControlEventTouchUpInside];
    [self.downView addSubview:self.playPause];
    
    //time
    self.timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(55, 20, 120, 20)];
    self.timeLabel.font = [UIFont systemFontOfSize:12.5];
    self.timeLabel.textColor = [UIColor whiteColor];
    self.timeLabel.textAlignment = NSTextAlignmentCenter;
    self.timeLabel.text = @"00:00/00:00";
    [self.downView addSubview:self.timeLabel];
    
    //进度条
    self.progress = [[UISlider alloc] initWithFrame:CGRectMake(180, 20, 667 - 270 + 14, 20)];
    
    self.progress.thumbTintColor = [UIColor clearColor];
    self.progress.minimumTrackTintColor = [UIColor grayColor];
    self.progress.maximumTrackTintColor = [UIColor clearColor];
    self.progress.userInteractionEnabled = NO;
    
    [self.downView addSubview:self.progress];

    
    //滑块
    self.slider = [[UISlider alloc] initWithFrame:CGRectMake(180, 20, CURRENTHEIGHT - 270, 20)];
    self.slider.maximumTrackTintColor = [UIColor colorWithRed:1.0 green:1.0 blue:1.0 alpha:0.2];
    [self.slider addTarget:self action:@selector(sliderUpAction) forControlEvents:UIControlEventTouchUpInside];
    [self.slider addTarget:self action:@selector(sliderValueChange) forControlEvents:UIControlEventValueChanged];
    [self.downView addSubview:self.slider];
    
    //初始化/获得播放器
    self.player = [self player];
    
    //轻拍屏幕事件的view
    UIView *bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 50, 667 - 150, 375 - 110)];
    
    [self.view addSubview:bgView];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    
    [bgView addGestureRecognizer:tap];
}

-(void)initMytableView{
    
    if (self.modelArray.count != 0) {
        
        self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(667, 50, 150, 375 - 110) style:UITableViewStylePlain];
        
        self.myTableView.backgroundColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.3];
        self.myTableView.dataSource = self;
        self.myTableView.delegate = self;
        self.myTableView.alpha = 0;
        self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        
        [self.view addSubview:self.myTableView];
    }else{
        self.selectedButton.alpha = 0;
    }
    
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _modelArray.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellIndentifier = @"mycell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIndentifier];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIndentifier];
    }
    
    if (self.titleArray.count > 0) {
        if (indexPath.row < self.titleArray.count) {
            
            NSString *str = [self.titleArray objectAtIndex:indexPath.row];
            cell.textLabel.text = str;
            
        }else{
            
            MovieModel *model = [self.modelArray objectAtIndex:indexPath.row];
            cell.textLabel.text = model.title;
        }
    }else{
        
        MovieModel *model = [self.modelArray objectAtIndex:indexPath.row];
        cell.textLabel.text = model.title;
    }
    cell.backgroundColor = [UIColor clearColor];
    cell.textLabel.textColor = [UIColor whiteColor];
    return cell;
}

//tableView点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    MovieModel *model = [self.modelArray objectAtIndex:indexPath.row];
    NSURL *url = [NSURL URLWithString:model.playUrl];
    
    if ([_MoviePlayUrl isEqualToString:model.playUrl]) {
        return;
    }
    
    NSString *text = @"";
    if (self.titleArray.count > 0 ) {
        if (indexPath.row < self.titleArray.count) {
            NSString *str = [self.titleArray objectAtIndex:indexPath.row];
            text = str;
        }else{
            text = [url absoluteString];
        }
    }else{
        text = [url absoluteString];
    }
    
    _MoviePlayUrl = [url absoluteString];
    
    [self removeObserverFromPlayerItem:self.player.currentItem];
    AVPlayerItem *playerItem = [self getPlayItem:[NSURL URLWithString:model.playUrl]];
    [self addObserverToPlayerItem:playerItem];
    // 切换视频
    [self.player replaceCurrentItemWithPlayerItem:playerItem];
    self.titleLabel.text = text;
    [self.player play];
    [self userEnble];
    [self hiddenAllViews];
}
//视图初始化

//*********************用户交互事件****************



//返回
-(void)backButtonAction{
    [self removeObserverFromPlayerItem:self.player.currentItem];
    [self dismissViewControllerAnimated:YES completion:nil];
}
//移除监控
-(void)removeObserverFromPlayerItem:(AVPlayerItem *)playerItem{
    
    //移除状态监控
    [playerItem removeObserver:self forKeyPath:@"status"];
    //
    [playerItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
    [self.player removeTimeObserver:_playBackObserver];
    //移除通知
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

//选集按钮
-(void)selectedAction{
    if (self.myTableView.alpha == 0) {
        [UIView animateWithDuration:0.3 animations:^{
            self.myTableView.frame = CGRectMake(667 - 150, 50, 150, 375 - 110);
            self.myTableView.alpha = 1;
        }];
    }else{
        self.myTableView.frame = CGRectMake(667, 50, 150, 375 - 110);
        self.myTableView.alpha = 0;
    }
}

//播放、停止按钮
-(void)playPauseAction{
    if (self.player.rate == 0) {
        //暂停状态
        [self.playPause setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
        [self.player play];
    }else if (self.player.rate == 1){
        //正在播放
        [self.player pause];
        [self.playPause setImage:[UIImage imageNamed:@"bofang"] forState:UIControlStateNormal];
    }
}
//
-(void)sliderUpAction{
    
    NSInteger drageSeconds = floorf(_slider.value);
    NSLog(@"dragedSeconds:%ld",drageSeconds);
    [_player pause];
    
    //转换成CMTime才能给player来控制播放进度
    CMTime dragedCMTime = CMTimeMake(drageSeconds, 1);
    
    __weak typeof(self) weakSelf = self;
    [self.player seekToTime:dragedCMTime completionHandler:^(BOOL finished) {
        [weakSelf.player play];
        weakSelf.isOperation = NO;
        [weakSelf hiddenMessageBox];
    }];
}

//sliderValue改变事件
-(void)sliderValueChange{
    
    self.isOperation = YES;
    NSString *text = [self convertTime:self.slider.value];
    [self showMessageBox:text];
}

-(void)tapAction{
    if (self.myTableView.alpha == 1 && self.downView.alpha != 1) {
        [UIView animateWithDuration:0.3 animations:^{
            self.myTableView.alpha = 0;
        }];
        
        return;
    }
    
    if (self.downView.alpha == 0) {
        [UIView animateWithDuration:0.3 animations:^{
            self.downView.alpha = 1;
            self.topView.alpha = 1;
            self.hiddenCount = 0;
        }];
    }else{
        [UIView animateWithDuration:0.3 animations:^{
            self.topView.alpha = 0;
            self.downView.alpha = 0;
            self.hiddenCount = 6;
            self.myTableView.alpha = 0;
        }];
    }
}


// 控件用户交互关闭
- (void)userEnble{
    self.selectedButton.userInteractionEnabled = NO;
    self.playPause.userInteractionEnabled = NO;
    self.slider.userInteractionEnabled = NO;
}
// 控件用户交互开启
- (void)userAble{
    self.selectedButton.userInteractionEnabled = YES;
    self.playPause.userInteractionEnabled = YES;
    self.slider.userInteractionEnabled = YES;
}

//展示提示框
-(void)showMessageBox:(NSString *)text{
    self.messageMark.alpha  = 1;
    self.messageMark.text = text;
    [self.view bringSubviewToFront:self.messageMark];
}
//隐藏提示框
-(void)hiddenMessageBox{
    self.messageMark.alpha = 0;
}

//隐藏所有控件
-(void)hiddenAllViews{
    [UIView animateWithDuration:0.3 animations:^{
        
        self.topView.alpha = 0;
        self.downView.alpha = 0;
        self.myTableView.alpha = 0;
    }];
}
//显示所有控件
-(void)showAllViews{
    [UIView animateWithDuration:0.3 animations:^{
        
        self.topView.alpha = 1;
        self.downView.alpha = 1;
        self.myTableView.alpha = 1;
    }];
}


//**************************播放器内部事件*********************

//初始化/获得播放器对象
-(AVPlayer *)player{
    if (!_player) {
        //如果不存在播放器对象
        AVPlayerItem *playerItem = [self getPlayItem:[NSURL URLWithString:self.MoviePlayUrl]];
        _player = [AVPlayer playerWithPlayerItem:playerItem];
        [self addObserverToPlayerItem:playerItem];
    }
    return _player;
    
}

/**
 *  根据视频索引取得AVPlayerItem对象
 *
 *  @param videoIndex 视频顺序索引
 *
 *  @return AVPlayerItem对象
 */
-(AVPlayerItem *)getPlayItem:(NSURL *)url{
    AVPlayerItem *playerItem = [AVPlayerItem playerItemWithURL:url];
    return playerItem;
}

//初始化子控件
-(void)setPlaySubviews{
    //创建播放器层
    AVPlayerLayer *playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    playerLayer.frame = self.container.frame;
    [self.container.layer addSublayer:playerLayer];
}


//给播放器单个播放对象AVPlayerItem添加监控
-(void)addObserverToPlayerItem:(AVPlayerItem *)playerItem{
    // 监控状态属性，注意AVPlayer也有一个status属性，通过监控它的status也可以获得播放状态
    [playerItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    
    //监控网络加载情况的属性
    [playerItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
}

/**
 *  通过KVO监控播放器状态
 *
 *  @param keyPath 监控属性
 *  @param object  监视器
 *  @param change  状态改变
 *  @param context 上下文
 */

-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
    
    AVPlayerItem *playerItem = object;
    
    if ([keyPath isEqualToString:@"status"]) {
        //监控的是状态
        AVPlayerStatus status = [[change objectForKey:@"new"] integerValue];
        if (status == AVPlayerStatusReadyToPlay) {
            //正在播放
            NSLog(@"正在播放...，视频总长度:%.2f", CMTimeGetSeconds(playerItem.duration));
            
            //视频总长度
            CMTime duration = playerItem.duration;
            self.slider.maximumValue = CMTimeGetSeconds(duration);
//            self.progress.ma
            //监听播放状态
            
            [self userAble]; //打开用户交互
        }
    }
}

#pragma mark - 监控
/**
 给播放器添加进度更新
 */

-(void)addProgressObserver{
    AVPlayerItem *playerItem = self.player.currentItem;
    
    __weak typeof (self) weakSelf = self;
    
    //设置每秒执行一次
    _playBackObserver = [weakSelf.player addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        CGFloat current = CMTimeGetSeconds(time);
        CGFloat total = CMTimeGetSeconds([playerItem duration]);
        
        NSString *currentStr = [weakSelf convertTime:current];
        NSString *totalStr = [weakSelf convertTime:total];
        
        weakSelf.timeLabel.text = [NSString stringWithFormat:@"%@/%@",currentStr,totalStr];
        NSLog(@"----当前播放时间%f--总%f", current, total);
        
        if (weakSelf.isOperation == NO) {
            //如果不在播放状态
            if (weakSelf.hiddenCount <= 8) {
                if (weakSelf.hiddenCount == 8) {
                    [weakSelf hiddenAllViews];
                }
                [weakSelf.slider setValue:current animated:YES];
            }
        }
    }];
}



-(NSString *)convertTime:(CGFloat)seconds{
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:seconds];
    if (seconds/3600 >= 1) {
        [[self dateFormatter] setDateFormat:@"HH:mm:ss"];
    } else {
        [[self dateFormatter] setDateFormat:@"mm:ss"];
    }
    NSString *showTimeNew = [[self dateFormatter] stringFromDate:date];
    
    return showTimeNew;
}

-(NSDateFormatter *)dateFormatter{
    if (!_dateFormatter) {
        _dateFormatter = [[NSDateFormatter alloc] init];
    }
    return _dateFormatter;

}


// ***************  强制横屏
- (BOOL)shouldAutorotate{
    
    return NO;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{
    
    return UIInterfaceOrientationLandscapeRight;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations{
    
    return UIInterfaceOrientationMaskLandscapeRight;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
